package com.atguigu.gulimall.order.listener;

import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 监听队列，完成秒杀商品的下单
 */
@RabbitListener(queues = "order.seckill.order.queue")
@Component
public class OrderSeckillListener {

    @Autowired
    OrderService orderService;

    /**
     * 监听MQ的消息队列，接受消息->实现：定时关闭订单功能
     */
    @RabbitHandler
    public void Listener(Message message, SeckillOrderTo seckillOrder, Channel channel) throws IOException {
        System.out.println("准备创建秒杀单的详细信息: " + seckillOrder.getOrderSn());
        try {
            orderService.createSeckillOrder(seckillOrder);
            //手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception ex) {
            //拒收消息且重新放入消息队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }


}
